package 多线程.练习.threadSemaphore;
import java.util.concurrent.Semaphore;

/**
 * 使用 Semphore 实现对双线程增加同一个变量
 */
public class ThreadSemaphore {
    public static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);

        Thread t1 = new Thread(() -> {
           for (int i = 0; i < 1000; i ++) {
               try {
                   semaphore.acquire();
                   count ++;
                   semaphore.release();
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i ++) {
                try {
                    // 尝试获取, 如果获取不到, 就会阻塞
                    semaphore.acquire();
                    count ++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count 的值为 : " + count);
    }
}
